package service

import (
	"context"
	"io"
	"time"

	"github.com/vmihailenco/msgpack"
)

type Context struct {
	*Conn
	context.Context
	cancel      func()
	uuid        string // user id
	IsAuthValid bool   // Is the auth valid
	Payload     io.Reader
	MsgType     MessageType
}

func newCtx() interface{} {
	//TODO
	return &Context{
		Conn:        nil,
		uuid:        "",
		IsAuthValid: false,
		Payload:     nil,
	}
}

func (c *Context) Reset(timeout time.Duration) {
	c.Context, c.cancel = context.WithTimeout(context.Background(), time.Second*5)
	c.Conn = nil
	c.uuid = ""
	c.IsAuthValid = false
	c.Payload = nil
	c.MsgType = 0
}

func (c *Context) Bind(i interface{}) error {
	return msgpack.NewDecoder(c.Payload).Decode(i)
}

func (s *ServiceImp) getCtx() *Context {
	ctx := s.ctxPool.Get().(*Context)
	ctx.Reset(s.handlerTimeout)
	return ctx
}

func (s *ServiceImp) returnCtx(ctx *Context) {
	ctx.cancel()
	s.ctxPool.Put(ctx)
}
